import request from '@/utils/request'

export interface User {
  id?: number;
  username: string;
  nickname: string;
  email: string;
  phone: string;
  role: '超级管理员' | '普通用户';
  status: '启用' | '禁用';
  createTime?: string;
}

export interface LoginRequest {
  username: string;
  password: string;
}

export interface LoginResponse {
  username: string;
  roles: string[];
  accessToken: string;
}

export interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

// 登录接口
export const userLogin = (data: LoginRequest) => {
  return request.post<ApiResponse<LoginResponse>>('/api/login', data)
}

// 刷新用户信息
export const refreshUserInfo = (token: string) => {
  return request.get<ApiResponse<LoginResponse>>('/api/userInfo', {
    headers: {
      Authorization: `Bearer ${token}`
    }
  })
}

// 获取用户列表
export const getUsers = () => {
  return request.get<ApiResponse<User[]>>('/api/users')
}

// 添加用户
export const addUser = (data: User) => {
  return request.post<ApiResponse<User>>('/api/user', data)
}

// 更新用户
export const updateUser = (data: User) => {
  return request.put<ApiResponse<User>>(`/api/user/${data.id}`, data)
}

// 删除用户
export const deleteUser = (id: number) => {
  return request.delete<ApiResponse<null>>(`/api/user/${id}`)
}

// 角色接口类型定义
export interface Role {
  id?: number;
  name: string;
  description: string;
  permissions: string[];
  createTime?: string;
}

// 获取角色列表
export const getRoles = () => {
  return request.get<ApiResponse<Role[]>>('/api/roles')
}

// 添加角色
export const addRole = (data: Role) => {
  return request.post<ApiResponse<Role>>('/api/role', data)
}

// 更新角色
export const updateRole = (data: Role) => {
  return request.put<ApiResponse<Role>>(`/api/role/${data.id}`, data)
}

// 删除角色
export const deleteRole = (id: number) => {
  return request.delete<ApiResponse<null>>(`/api/role/${id}`)
}

// 权限类型定义
export interface Permission {
  id: string;
  name: string;
  code: string;
  children?: Permission[];
}

// 获取所有权限列表
export const getPermissions = () => {
  return request.get<ApiResponse<Permission[]>>('/api/permissions')
}